#!/bin/sh

# 设置当有命令错误时立即退出选项
set -e

WORKDIR=$(cd `dirname $0`; pwd)
BASE_FILE=${WORKDIR}/logs
GC_FILE=${BASE_FILE}/gc_logs
WAIT_TIME=2
LOG_LEVEL=t1

function get_date(){
    date +%Y-%m-%d\ %H:%M:%S
}

function made_env(){
    echo -en "applo ${APOLLO_TAG} config file making ... "
    mkdir /opt/case/tongyong_conf/apollo -p
    echo "idc=${APOLLO_TAG}" > /opt/case/tongyong_conf/apollo/server.properties
    echo "env=UAT" >> /opt/case/tongyong_conf/apollo/server.properties
    echo "uat_meta=http://t1-managerdaikuan.2345.com:8080" >> /opt/case/tongyong_conf/apollo/server.properties
    echo "done"
}

function jar_start(){
    echo "`get_date` [PRECHECK] $SERVICE.jar check ... "
    if [ -f $WORKDIR/$SERVICE.jar ]; then
        java -server -Xms${MIN_RESOURCE} -Xmx${MAX_RESOURCE} \
        -Dspring.profiles.active=${LOG_LEVEL} -jar ${SERVICE}.jar \
        --server.port=${HTTP_PORT} --spring.profiles.active=${LOG_LEVEL} \
        -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=3 \
        -XX:GCLogFileSize=128M -XX:+PrintGC -XX:+PrintGCDetails \
        -XX:+PrintGCTimeStamps -XX:+PrintTenuringDistribution  > : &
    else
        echo "$SERVICE.jar not found, please check, see you around!"
        exit 1
    fi
}

function tomcat_start(){
    echo "`get_date` [PRECHECK] $SERVICE.war check ... "
    if [ -f $WORKDIR/webapps/$SERVICE.war ]; then
        sed -i "109aJAVA_OPTS=\" -server $JAVA_OPTS -Xms$MIN_RESOURCE -Xmx$MAX_RESOURCE -XX:MetaspaceSize=200M -XX:MaxMetaspaceSize=200M \"" bin/catalina.sh
        # 启动tomcat命令
        catalina.sh run > : &
    else
        echo "$SERVICE.war not found, please check, see you around!"
        exit 1
    fi
}

function start {
# 检查必要的启动参数
echo "`get_date` [PRECHECK] Check the neccessary env to start a app"

# 环境名称
echo -en "APOLLO_TAG ... "
if [ x$APOLLO_TAG == x ];then
    echo "error"
    echo "APOLLO_TAG can't be empty, please check, see you around!"
    exit 1
else
    echo "$APOLLO_TAG"
    made_env
fi

# 日志文件名称
echo -en "LOGS_FILE ... "
if [ x$LOGS_FILE == x ];then
    echo "error"
    echo "LOGS_FILE can't be empty, please check, see you around!"
    exit 1
else
    echo "$LOGS_FILE"

fi

# 检查配置的资源大小
echo -en "MIN_RESOURCE ... "
if [ x$MIN_RESOURCE == x ];then
    echo "error"
    echo "MIN_RESOURCE can't be empty, please check, see you around!"
    exit 1
else
    echo "$MIN_RESOURCE"
fi

echo -en "MAX_RESOURCE ... "
if [ x$MAX_RESOURCE == x ];then
    echo "error"
    echo "MIN_RESOURCE can't be empty, please check, see you around!"
    exit 1
else
    echo "$MAX_RESOURCE"
fi

# 应用类型
echo -en "TYPE ... "
if [ x$TYPE == xJAR ];then
    echo "jar"
    jar_start
elif [ x$TYPE == xTOMCAT ];then
    echo "tomcat"
    tomcat_start
else
    echo "ERROR"
    echo "TYPE only support JAR or TOMCAT, plasea check, see you around!"
    exit 1
fi
}

function output {
while [ ! -f ${BASE_FILE}/$LOGS_FILE ]
do
   sleep $WAIT_TIME
done
tail -F ${BASE_FILE}/$LOGS_FILE
}

function main {
    start
    output
}

main